#include "mainwindow.h"
#include "ui_mainwindow.h"
/*
    modbus-master
    xx        xx      xx xx      xx xx    xx xx
    设备地址  功能码   G存器地址    size    CRC校验
    such as：
    01      03    0F A1    00 12    97 31
*/
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//ui调整
    setWindowIcon(QIcon(":/qt/etc/logo.ico"));

    modbusDevice = new QModbusRtuSerialMaster();  //创建 对象modbus
    portList     = new SerialPortList(200);       //创建对象 串口列表
    portList->ScanStart();                        //开启扫描
    connect(portList, SIGNAL(onNewSerialPort(QStringList)),this,SLOT(onNewPortList(QStringList)));//自动扫描端口
    statusBar()->showMessage("未连接");

    //串口配置初始化ui
    ui->baudQcomboBox->addItem("4800");
    ui->baudQcomboBox->addItem("9600");
    ui->baudQcomboBox->addItem("38400");
    ui->baudQcomboBox->addItem("115200");
    ui->baudQcomboBox->addItem("512000");
    ui->baudQcomboBox->setCurrentIndex(3);

    ui->dataQcomboBox->addItem("5");
    ui->dataQcomboBox->addItem("6");
    ui->dataQcomboBox->addItem("7");
    ui->dataQcomboBox->addItem("8");
    ui->dataQcomboBox->setCurrentIndex(3);

    ui->valQcomboBox->addItem("none",0);
    ui->valQcomboBox->addItem("even",2);
    ui->valQcomboBox->addItem("odd",3);
    ui->valQcomboBox->addItem("space",4);
    ui->valQcomboBox->addItem("mark",5);
    ui->valQcomboBox->setCurrentIndex(0);

    ui->stopQcomboBox->addItem("one","1");
    ui->stopQcomboBox->addItem("two","2");
    ui->stopQcomboBox->addItem("oneAndHalfStop","3");
    ui->stopQcomboBox->setCurrentIndex(0);

    ui->hexQcheckBox->setChecked(false);
    QImage image;
    image.load(":/qt/etc/basketball.png");
    ui->label->setPixmap(QPixmap::fromImage(image));
    ui->label_12->setPixmap(QPixmap::fromImage(image));

}


MainWindow::~MainWindow()
{
    delete ui;
    delete modbusDevice;
}

void MainWindow::onNewPortList(QStringList portName){  // 自动连接槽
    ui->portQcomboBox->clear();
    ui->portQcomboBox->addItems(portName);
}
//连接按钮
void MainWindow::on_connectQpushButton_clicked(){
    portAddr = ui->addrQspinBox->value(); //获取modbus地址
    qDebug() << portAddr;
    if(ui->connectQpushButton->text() == "连接"){
        if(modbusDevice->state() != QModbusDevice::ClosingState){//若没连接

            modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter,ui->portQcomboBox->currentText());

            modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter,(ui->valQcomboBox->currentData()).toInt());

            modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,(ui->baudQcomboBox->currentText()).toInt());

            modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,(ui->dataQcomboBox->currentText()).toInt());
            modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,(ui->stopQcomboBox->currentData().toInt()));

            modbusDevice->setTimeout(1000);

            modbusDevice->setNumberOfRetries(3);

            if(!modbusDevice->connectDevice()){
                qDebug() << "connect fail!!";
            }
            else {
                ui->connectQpushButton->setText("关闭");
                statusBar()->showMessage("已连接");
            }
        }
    }
    else{                  //若已连接。则断开
        modbusDevice->disconnectDevice();
        ui->connectQpushButton->setText("连接");
        statusBar()->showMessage("未连接");
    }

}

void MainWindow::on_testQpushButton_clicked()
{

    if(ui->connectQpushButton->text() == "连接"){
        QMessageBox msgBox;
        msgBox.setText("无设备！！");
        msgBox.exec();
        return ;
    }
    code = (ui->codeQelineEdit->text()).toInt();
    dateSize = (ui->sizeQlineEdit->text()).toInt();
    slaveRegister = (ui->GQlineEdit->text()).toInt();
    QModbusReply *reply;

    switch (code){
        case 1:
            reply = modbusDevice->sendReadRequest(QModbusDataUnit(QModbusDataUnit::DiscreteInputs, slaveRegister, dateSize), portAddr);break;
        case 2:
            reply = modbusDevice->sendReadRequest(QModbusDataUnit(QModbusDataUnit::Coils, slaveRegister, dateSize), portAddr);break;
        case 4:
            reply = modbusDevice->sendReadRequest(QModbusDataUnit(QModbusDataUnit::InputRegisters, slaveRegister, dateSize), portAddr);break;
        case 3:
            reply = modbusDevice->sendReadRequest(QModbusDataUnit(QModbusDataUnit::HoldingRegisters, slaveRegister, dateSize), portAddr);break;
    }


    connect(reply, &QModbusReply::finished, this, [this, reply]()//收到modbus finised信号
                {
                        str.clear();
                        for(int i = 0; i < dateSize; i++){
                            if( hexMod == 1)
                                str = str + QString::number(reply->result().value(i),16) + " ";
                            else
                                str = str + QString::number(reply->result().value(i),10) + " ";
                        }
                        //qDebug() << str;
                        reply->deleteLater();
                        ui->textBrowser->append(str);
                        qDebug()<<reply->QModbusReply::isFinished();
                });

}

void MainWindow::on_writeQpushButton_clicked()
{
    int dataBuf;
    bool ok;
    if(ui->connectQpushButton->text() == "连接"){
        QMessageBox msgBox;
        msgBox.setText("无设备！！");
        msgBox.exec();
        return ;
    }
    QModbusDataUnit writeBuf;
    QModbusReply *reply;
    dateSize = (ui->sizeQlineEdit->text()).toInt();
    slaveRegister = (ui->GQlineEdit->text()).toInt();
    if(hexMod == 1)
        dataBuf = (ui->dataQlineEdit->text()).toInt(&ok, 16);
    else{
        if((ui->dataQlineEdit->text()).contains(QRegExp("[a-Z]"))){//若有字母
            QMessageBox msgBox;
            msgBox.setText("10进制模式不可输入字母！！");
            msgBox.exec();
            return ;
        }
        dataBuf = (ui->dataQlineEdit->text()).toInt(&ok, 10);

    }
    writeBuf = QModbusDataUnit(QModbusDataUnit::HoldingRegisters, slaveRegister, 1);

    writeBuf.setValue(0, dataBuf);
//    writeBuf.setValue(1, dataBuf+1);
//    writeBuf.setValue(2, dataBuf-1);

    reply = modbusDevice->sendWriteRequest(writeBuf, portAddr);
    connect(reply, &QModbusReply::finished, this, [this, reply]()
            {
               reply->deleteLater();
             });

}

void MainWindow::on_hexQcheckBox_stateChanged(int arg1)
{
    if(arg1 == Qt::Checked){
        hexMod = 1;//开启
    }
    if( arg1 == Qt::Unchecked){
        hexMod = 0;
    }
}
void MainWindow::on_clearQpushButton_clicked()
{
    ui->textBrowser->clear();
}
